package com.vcourse.service.base.handler;

import com.vcourse.commons.result.R;
import com.vcourse.commons.result.ResultCodeEnum;
import com.vcourse.commons.utils.ExceptionUtils;
import com.vcourse.service.base.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author Zengsh123
 * @date 2020-05-26 15:24
 * 全局异常处理
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R error(Exception e) {
        log.error(ExceptionUtils.getMessage(e));
        return R.error();
    }

    @ExceptionHandler(BadSqlGrammarException.class)
    @ResponseBody
    public R error(BadSqlGrammarException e) {
        log.error(ExceptionUtils.getMessage(e));
        return R.setResult(ResultCodeEnum.BAD_SQL_GRAMMAR);
    }

    /**
     * 自定义异常拦截
     * @param e 自定义异常
     */
    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public R error(CustomException e) {
        log.error(ExceptionUtils.getMessage(e));
        return R.error().code(e.getCode()).message(e.getMessage());
    }
}
